import { View } from '@tarojs/components';
import s from './index.module.scss'
import Icon from 'components/Icon'
import { useEffect, useRef, useState } from 'react';
import classNames from 'classnames';
import Taro from '@tarojs/taro';

interface ShowProps{
  title:string,
  desc:string,
  renderCode?: any,
  children?: any,
  btn?: any,
  codeTabs: {filename: string, code: () => JSX.Element}[],
  adtype?: 'ad15' | 'ad30' | 'ad60'
}

export const ads = {
  ad15: 'adunit-8b740ae4c99e44ac',
  ad30: 'adunit-6dfce0e82b225be2',
  ad60: 'adunit-6156e5071459d547'
}

export default function CodeCard(props: ShowProps) {
  const { title, desc, renderCode, children, codeTabs = [], adtype} = props
  const [show, setShow] = useState(!adtype)
  const [current, setCurrent] = useState(0)
  const ad = useRef<any>(null)
  const [locked, setLoacked] = useState(!!adtype)

  const __btn_wrapper = classNames(s.button, {
    [s.show]: show
  })

  const __nav_item = (index) => classNames(s.nav_item, {
    [s.active]: current === index
  })

  useEffect(() => {
    if (!adtype) return
    ad.current = Taro.createRewardedVideoAd({
      adUnitId: ads[adtype]
    })
    ad.current.onLoad(() => {})
    ad.current.onError(err => {
      console.log(err)
      setLoacked(false)
      setShow(true)
    })
    ad.current.onClose((res) => {
      if (res.isEnded) {
        setLoacked(false)
        setShow(true)
      }
      if (!res.isEnded) {
      }
    })
  }, [])

  function clickShowToHandler() {
    if (adtype && locked) {
      ad.current.show()
    }
    else { 
      setShow(!show)
    }
  }

  return (
    <View className={s.code_wrapper}>
      <View className={s.section}>
        <View className={s.playground}>{children}</View>
        <View className={s.line}>
          <View className={s.code_title}>{title}</View>
        </View>
        <View className={s.description}>{desc}</View>
        <View className={__btn_wrapper}>
          <div id={s.btn_tip}>{locked ? '点击观看广告，解锁源码 -->' : '源码已解锁'}</div>
          <View className={s.icon_box} onClick={clickShowToHandler}>
            <Icon name='chevron-down' size={26} style={{ transform: 'rotate(90deg)', marginRight: '-10px' }} />
            <Icon name='chevron-up' size={26} style={{ transform: 'rotate(90deg)' }} />
          </View>
        </View>
       
        {show && codeTabs.length === 0 ? (
          <View className='code_container'>
            {renderCode()}
          </View>
        ) : null}
        {show && codeTabs.length > 0 ? (
          <>
            <View className={s.nav_wrapper}>
              {codeTabs.map((item, index) => (
                <View 
                  className={__nav_item(index)} 
                  key={item.filename}
                  onClick={() => setCurrent(index)}
                >{item.filename}</View>
              ))}
            </View>
            {codeTabs[current].code()}    
          </>
        ) : null}
      </View>
    </View>
  )
}